<template>
  <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
    <el-form ref="pickupForm" :model="pickupForm" :rules="rules" label-width="120px">
      <el-form-item label="审批请求ID" prop="approvalRequestId">
        <el-input v-model="pickupForm.approvalRequestId" disabled />
      </el-form-item>
      <el-form-item label="车辆信息" prop="sysVechicleDto">
        <el-table :data="pickupForm.sysVechicleDto" border style="width: 100%">
          <el-table-column label="车牌号" align="center" prop="licensePlate" />
          <el-table-column label="品牌" align="center" prop="brand" />
          <el-table-column label="购车年份" align="center" prop="purchaseYear" />
          <el-table-column label="单位名称" align="center" prop="organizationName" />
          <el-table-column label="车辆类型" align="center" prop="type" />
          <el-table-column label="座位数" align="center" prop="seatCount" />
          <el-table-column label="驾驶员" align="center" prop="driver" />
          <el-table-column label="图片" align="center" width="120">
            <template slot-scope="scope">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.image"
                fit="cover"
              />
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px;">
          <el-button type="primary" @click="addVehicle">增加车辆</el-button>
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="pickupForm.remarks" type="textarea" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </div>
    <SelectVehicleDialog
      ref="vehicleSelectionDialog"
      :open.sync="vehicleSelectionDialogOpen"
      :vehicles="vehicleSelectionList"
      :isRemoving="isRemoving"
      @submit="handleVehicleSelection"
    />
  </el-dialog>
</template>

<script>
import SelectVehicleDialog from "@/views/vehicles/vehicles/SelectVehicleDialog.vue";

export default {
  name: "PickupDialog",
  components: {
    SelectVehicleDialog
  },
  props: {
    open: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      title: "提车",
      pickupForm: {
        approvalRequestId: null,
        sysVechicleDto: [],
        remarks: ''
      },
      rules: {
        sysVechicleDto: [
          { required: true, message: '请选择车辆', trigger: 'change' }
        ],
        remarks: [
          { required: true, message: '请输入备注', trigger: 'blur' }
        ]
      },
      freeVehicles: [],
      vehicleSelectionDialogOpen: false,
      vehicleSelectionList: [],
      isRemoving: false
    };
  },
  watch: {
    open(val) {
      if (val) {
        this.initForm();
      }
    }
  },
  methods: {
    initForm() {
      this.pickupForm.approvalRequestId = this.row.approvalRequestsId;
      this.pickupForm.sysVechicleDto = this.row.sysVechicleDto;
      this.getFreeVehicles(); // 获取空闲车辆
    },
    cancel() {
      this.$emit('update:open', false);
      this.resetForm();
    },
    resetForm() {
      this.pickupForm = {
        approvalRequestId: null,
        sysVechicleDto: [],
        remarks: ''
      };
      this.$refs['pickupForm'].resetFields();
    },
    submitForm() {
      this.$refs['pickupForm'].validate(valid => {
        if (valid) {
          const data = {
            approvalRequestId: this.pickupForm.approvalRequestId,
            sysVehicles: this.pickupForm.sysVechicleDto.map(vehicle => ({
              id: vehicle.id,
              licensePlate: vehicle.licensePlate
            })),
            remarks: this.pickupForm.remarks
          };
          this.$emit('submit', data);
          this.cancel();
        }
      });
    },
    getFreeVehicles() {
      // 假设有一个 API 来获取空闲车辆
      listRecords().then(response => {
        this.freeVehicles = response.data.filter(vehicle =>
          !this.pickupForm.sysVechicleDto.some(selectedVehicle => selectedVehicle.id === vehicle.id)
        );
      }).catch(error => {
        this.$modal.msgError("获取空闲车辆失败");
      });
    },
    addVehicle() {
      this.vehicleSelectionList = this.freeVehicles;
      this.isRemoving = false;
      this.vehicleSelectionDialogOpen = true;
    },
    removeVehicle() {
      if (this.pickupForm.sysVechicleDto.length <= 1) {
        this.$modal.msgError("至少选择一辆车");
        return;
      }
      this.vehicleSelectionList = this.pickupForm.sysVechicleDto;
      this.isRemoving = true;
      this.vehicleSelectionDialogOpen = true;
    },
    handleVehicleSelection(selectedVehicles, isRemoving) {
      if (isRemoving) {
        this.pickupForm.sysVechicleDto = selectedVehicles;
      } else {
        this.pickupForm.sysVechicleDto = [
          ...this.pickupForm.sysVechicleDto,
          ...selectedVehicles.filter(vehicle =>
            !this.pickupForm.sysVechicleDto.some(selectedVehicle => selectedVehicle.id === vehicle.id)
          )
        ];
      }
      this.vehicleSelectionDialogOpen = false; // 关闭对话框
    }
  }
};
</script>
